#!/usr/bin/env python
# Author Will Zhe Zhang
# Login zzha
# SID 304914


"""
Loader script for XDXF dictionaries.

A word entry in XDXF format is structured like the following example:

<ar><k>Australia</k>
Australie</ar>

The resulting element object of tag <k> has:
elem.text = 'Australia'
elem.tail = 'Australie'

"""

from collections import defaultdict
from xml.etree import ElementTree

def load(xdxf_file):
    dict = defaultdict(set)
    tree = ElementTree.ElementTree()
    #Parse XML into tree
    tree.parse(xdxf_file)
    #Search all articles in tree
    articles = tree.findall('ar/k')
    for article in articles:
        #Text inside <k> tags are keys
        key = article.text
        #Tail string is the list of values
        # remove leading newline character and split
        values = article.tail.lstrip('\n').split(', ')
        #Populate target dictionary with new entry
        for value in values:
            dict[key].add(value)
    return dict
    
if __name__ == "__main__":
    dict_file = "dict.xdxf"
    dict = load(dict_file)
    for key in sorted(dict.keys()):
        print key+': '+"; ".join(dict[key])
